"""
BOM模块字典工具函数
用于从数据库获取字典数据并提供给模型使用
"""

from typing import Dict, List, Optional, Any
from functools import lru_cache
from django.db import transaction
from system.models import DictType, DictData


def get_dict_data_by_type(dict_type_value: str) -> Dict[str, Any]:
    """
    根据字典类型值获取字典数据
    
    Args:
        dict_type_value: 字典类型值
        
    Returns:
        Dict: 字典数据，格式为 {value: label}
    """
    try:
        dict_type = DictType.objects.get(value=dict_type_value, status=True)
        dict_data = DictData.objects.filter(dict_type=dict_type, status=True).order_by('sort')
        return {item.value: item.label for item in dict_data}
    except DictType.DoesNotExist:
        return {}


def get_dict_item_by_value(dict_type_value: str, item_value: str) -> Optional[str]:
    """
    根据字典类型值和项目值获取单个字典项的标签
    
    Args:
        dict_type_value: 字典类型值
        item_value: 字典项值
        
    Returns:
        Optional[str]: 字典项标签，如果不存在则返回None
    """
    try:
        dict_type = DictType.objects.get(value=dict_type_value, status=True)
        dict_item = DictData.objects.get(
            dict_type=dict_type, 
            value=item_value, 
            status=True
        )
        return dict_item.label
    except (DictType.DoesNotExist, DictData.DoesNotExist):
        return None


def get_dict_label_by_value(dict_type_value: str, item_value: str) -> str:
    """
    根据字典类型值和项目值获取单个字典项的标签，如果不存在则返回原值
    
    Args:
        dict_type_value: 字典类型值
        item_value: 字典项值
        
    Returns:
        str: 字典项标签，如果不存在则返回原值
    """
    label = get_dict_item_by_value(dict_type_value, item_value)
    return label if label is not None else item_value


@lru_cache(maxsize=128)
def get_cached_dict_data_by_type(dict_type_value: str) -> Dict[str, Any]:
    """
    根据字典类型值获取字典数据（带缓存）
    
    Args:
        dict_type_value: 字典类型值
        
    Returns:
        Dict: 字典数据，格式为 {value: label}
    """
    return get_dict_data_by_type(dict_type_value)


def get_dict_data_with_details(dict_type_value: str) -> List[Dict[str, Any]]:
    """
    根据字典类型值获取字典数据详情
    
    Args:
        dict_type_value: 字典类型值
        
    Returns:
        List[Dict]: 字典数据详情列表，包含value, label, sort, color_type, css_class等字段
    """
    try:
        dict_type = DictType.objects.get(value=dict_type_value, status=True)
        dict_data = DictData.objects.filter(dict_type=dict_type, status=True).order_by('sort')
        return [
            {
                'value': item.value,
                'label': item.label,
                'sort': item.sort,
                'color_type': item.color_type,
                'css_class': item.css_class,
                'remark': item.remark
            }
            for item in dict_data
        ]
    except DictType.DoesNotExist:
        return []


def refresh_dict_cache():
    """刷新字典缓存"""
    get_cached_dict_data_by_type.cache_clear()


def init_dict_data_if_not_exists():
    """如果字典数据不存在，则初始化"""
    from .init_dict_data import init_bom_dict_data
    init_bom_dict_data()


# 常用字典类型常量
BOM_TYPE_DICT = 'bom_type'
BOM_STATUS_DICT = 'bom_status'
LIFECYCLE_STATUS_DICT = 'lifecycle_status'
MATERIAL_TYPE_DICT = 'material_type'
BOM_VERSION_STATUS_DICT = 'bom_version_status'
BOM_CHANGE_TYPE_DICT = 'bom_change_type'
BOM_COST_TYPE_DICT = 'bom_cost_type'
BOM_COST_METHOD_DICT = 'bom_cost_method'
BOM_SIMULATION_TYPE_DICT = 'bom_simulation_type'
BOM_REPORT_TYPE_DICT = 'bom_report_type'
BOM_PERMISSION_TYPE_DICT = 'bom_permission_type'
BOM_FLOW_TYPE_DICT = 'bom_flow_type'
BOM_FLOW_STATUS_DICT = 'bom_flow_status'
BOM_STEP_TYPE_DICT = 'bom_step_type'
BOM_STEP_STATUS_DICT = 'bom_step_status'
ALT_MATERIAL_STATUS_DICT = 'alt_material_status'
DOCUMENT_TYPE_DICT = 'document_type'